-- Lua Battle System - 表操作工具

local TableUtils = {}

-- 深拷贝表
function TableUtils.deep_copy(tbl)
    if type(tbl) ~= "table" then
        return tbl
    end
    
    local copy = {}
    for key, value in pairs(tbl) do
        copy[key] = TableUtils.deep_copy(value)
    end
    
    return copy
end

-- 合并表
function TableUtils.merge(tbl1, tbl2)
    local result = TableUtils.deep_copy(tbl1)
    
    for key, value in pairs(tbl2) do
        if type(result[key]) == "table" and type(value) == "table" then
            result[key] = TableUtils.merge(result[key], value)
        else
            result[key] = value
        end
    end
    
    return result
end

-- 获取表长度
function TableUtils.length(tbl)
    local count = 0
    for _ in pairs(tbl) do
        count = count + 1
    end
    return count
end

-- 检查表是否为空
function TableUtils.is_empty(tbl)
    return next(tbl) == nil
end

-- 克隆表（浅拷贝）
function TableUtils.clone(tbl)
    if type(tbl) ~= "table" then
        return tbl
    end
    
    local copy = {}
    for key, value in pairs(tbl) do
        copy[key] = value
    end
    
    return copy
end

-- 查找表中的值
function TableUtils.find(tbl, value)
    for key, val in pairs(tbl) do
        if val == value then
            return key
        end
    end
    return nil
end

-- 过滤表
function TableUtils.filter(tbl, predicate)
    local result = {}
    for key, value in pairs(tbl) do
        if predicate(key, value) then
            result[key] = value
        end
    end
    return result
end

-- 映射表
function TableUtils.map(tbl, mapper)
    local result = {}
    for key, value in pairs(tbl) do
        result[key] = mapper(key, value)
    end
    return result
end

-- 遍历表
function TableUtils.foreach(tbl, callback)
    for key, value in pairs(tbl) do
        callback(key, value)
    end
end

-- 遍历数组
function TableUtils.foreachi(tbl, callback)
    for i, value in ipairs(tbl) do
        callback(i, value)
    end
end

-- 表转字符串
function TableUtils.to_string(tbl, indent)
    indent = indent or 0
    local str = "{\n"
    local indent_str = string.rep("  ", indent + 1)
    
    for key, value in pairs(tbl) do
        local key_str
        if type(key) == "string" then
            key_str = string.format("%q", key)
        else
            key_str = tostring(key)
        end
        
        local value_str
        if type(value) == "table" then
            value_str = TableUtils.to_string(value, indent + 1)
        elseif type(value) == "string" then
            value_str = string.format("%q", value)
        else
            value_str = tostring(value)
        end
        
        str = str .. indent_str .. key_str .. " = " .. value_str .. ",\n"
    end
    
    str = str .. string.rep("  ", indent) .. "}"
    return str
end

-- 导出模块
return TableUtils